{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "import json\n",
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "from PIL import Image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[{'name': 'input_1', 'index': 1, 'shape': array([  1, 224, 224,   3], dtype=int32), 'dtype': <class 'numpy.float32'>, 'quantization': (0.0, 0)}]\n",
      "[{'name': 'Identity', 'index': 0, 'shape': array([ 1, 40], dtype=int32), 'dtype': <class 'numpy.float32'>, 'quantization': (0.0, 0)}]\n"
     ]
    }
   ],
   "source": [
    "# 加载模型并分配张量\n",
    "interpreter = tf.lite.Interpreter(model_path=\"./converted_model.tflite\")\n",
    "interpreter.allocate_tensors()\n",
    "# 获取输入输出张量\n",
    "input_details = interpreter.get_input_details()\n",
    "output_details = interpreter.get_output_details()\n",
    "print(input_details)\n",
    "print(output_details)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "#加载分类\n",
    "with open(\"./garbage_classify_rule.json\", 'r') as load_f:\n",
    "            load_dict = json.load(load_f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Time used: 1.0005250000000006 ms\n",
      "36\n",
      "可回收物/饮料瓶\n"
     ]
    }
   ],
   "source": [
    "\n",
    "image = Image.open('./test4.png').convert('RGB').resize(\n",
    "            (224, 224), Image.ANTIALIAS)\n",
    "image = np.array(image,dtype=np.float32).reshape(input_details[0]['shape'])\n",
    "start = time.clock() #计算时间\n",
    "interpreter.set_tensor(input_details[0]['index'],image)\n",
    "interpreter.invoke()\n",
    "output_data = interpreter.get_tensor(output_details[0]['index'])\n",
    "pred_label = np.argmax(output_data[0])\n",
    "elapsed = (time.clock() - start)\n",
    "print(\"Time used:\",elapsed,\"ms\")\n",
    "print(pred_label)\n",
    "print(load_dict[str(pred_label)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.7.6 64-bit ('keras-learn': conda)",
   "language": "python",
   "name": "python37664bitkeraslearnconda3cfe7c237a504526967beae8949618e3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
